package org.prototype.bank.dao.jdbc;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.prototype.bank.dao.TransactionDao;
import org.prototype.bank.domain.Account;
import org.prototype.bank.domain.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class JdbcTransactionDao implements TransactionDao {
	protected final Logger logger = Logger.getLogger(getClass());

	private SimpleJdbcTemplate simpleJdbcTemplate;
	private SimpleJdbcInsert insertTransaction;

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
		this.insertTransaction = new SimpleJdbcInsert(dataSource).withTableName(
				"transaction").usingGeneratedKeyColumns("ID");
	}
	
	public Transaction createTransaction(Account fromAccount,
			Account toAccount, double amount) {
		Date currentTime = new Date();
		Map<String, Object> parematers = new HashMap<String, Object>();
		parematers.put("FROM_ACCOUNT_ID", fromAccount.getAccountId());
		parematers.put("TO_ACCOUNT_ID", toAccount.getAccountId());
		parematers.put("AMOUNT", new Double(amount));
		parematers.put("TRANS_TIME", currentTime);
		Number newId = insertTransaction.executeAndReturnKey(parematers);
		
		Transaction transaction = new Transaction(fromAccount, toAccount, amount, currentTime);
		transaction.setId(newId.longValue());
		return transaction;
	}

	public int countTransactions(){
		String sql = "SELECT count(1) FROM transaction";
		return this.simpleJdbcTemplate.queryForInt(sql);
	}
}
